package com.xujiang.myblog.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.xujiang.common.util.ToolBarHelper;
import com.xujiang.myblog.Base.CPRXFragment;
import com.xujiang.myblog.R;
import com.xujiang.myblog.adapter.UserFragemtAdapter;
import com.xujiang.myblog.entity.UserFragmentEntity;
import com.xujiang.myblog.entity.UserShow;
import com.xujiang.myblog.model.AccessToken;
import com.xujiang.myblog.model.HeadPicture;
import com.xujiang.myblog.model.PreferUser;
import com.xujiang.myblog.network.retrofit.MRetrifit;
import com.xujiang.myblog.ui.LoginActivity;
import com.xujiang.myblog.util.CPProgressDialog;
import com.xujiang.myblog.util.Callback;
import com.xujiang.myblog.util.Callback2;
import com.xujiang.myblog.util.Callback4;
import com.xujiang.myblog.util.L;
import com.xujiang.myblog.util.TakeImagesHelper;
import com.xujiang.myblog.util.UIUtils;
import com.xujiang.myblog.util.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.glide.transformations.CropCircleTransformation;
import rx.Subscription;

import static com.xujiang.myblog.entity.UserFragmentEntity.CLICK_ITEM_CHILD_VIEW;
import static com.xujiang.myblog.entity.UserFragmentEntity.CLICK_ITEM_VIEW;
import static com.xujiang.myblog.entity.UserFragmentEntity.NEST_CLICK_ITEM_CHILD_VIEW;

/**
 * Created by xujiang on 2017/4/12.
 */

public class UserFragment extends CPRXFragment {

    private static final String TAG = UserFragment.class.getSimpleName();
    @BindView(R.id.RCV_User_Fragment)
    RecyclerView RCVUserFragment;

    private UserFragemtAdapter adapter;

    CPProgressDialog mProgressDialog;

    Subscription uploadAvatarSubscription;

    TakeImagesHelper mTakeImagesHelper;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user, container, false);
        ButterKnife.bind(this, view);

        RCVUserFragment.setHasFixedSize(true);
        RCVUserFragment.setLayoutManager(new LinearLayoutManager(getContext()));

        initAdapter();

        mTakeImagesHelper = TakeImagesHelper.with(this);   //关于头像的帮助类  来自第三方
        mProgressDialog = new CPProgressDialog(getContext());
        mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                Utils.unsubscribe(uploadAvatarSubscription);
            }
        });
        initToolbar(view);
        L.i(TAG, "UserFragment Blog Fragment");
        return view;
    }

    private void initToolbar(View view) {
        ToolBarHelper toolbarhelper = ToolBarHelper.with(view);
        Toolbar toolbar = toolbarhelper.getToolbar();
        try {
            setAll(toolbar, R.mipmap.ic_launcher, R.mipmap.user_portrait_hint_sm,
                    "Title test can show how long", "SubTitle test can show how long",
                    R.menu.base_toolbar_menu);
            setDefaultOnclicklistener(toolbar);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initAdapter() {
        adapter = new UserFragemtAdapter(getData(), getContext());
        adapter.openLoadAnimation();
        //adapter.setNotDoAnimationCount(5); ////设置第一页加载数量
        RCVUserFragment.setAdapter(adapter);

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.user_avatars_imv_userfragment:
                        //http://blog.csdn.net/ydxlt/article/details/48024017
                        mTakeImagesHelper.showTakeImageDialog(new Callback2.EmptyCallback<String>() {
                            @Override
                            public void onSuccess(String s) {
                                L.i(TAG, s);
                                upload(s, (ImageView) view);
                            }

                            @Override
                            public void onError(Throwable e) {
                                L.getToast().e(TAG, getContext(), e);
                            }

                        });
                        break;

                    case R.id.user_rl:
                        if (!PreferUser.get().isLogin()) {
                            UIUtils.startActivity(getActivity(), LoginActivity.class);
                        }

                        break;

                    case R.id.ll_myblog:
                        Toast.makeText(getContext(), "user 点击ll_myblog", Toast.LENGTH_SHORT).show();
                        break;

                    case R.id.ll_seemyblog:
                        Toast.makeText(getContext(), "user 点击ll_seemyblog", Toast.LENGTH_SHORT).show();
                        break;

                    case R.id.ll_fans:
                        Toast.makeText(getContext(), "user 点击ll_fans", Toast.LENGTH_SHORT).show();
                        break;

                    case R.id.cv_logout_userfragment:
                        if (!PreferUser.get().isLogin()) {
                            return;
                        }
                        UIUtils.showYNAlertDialog(getContext(), "Sign Out?", false,
                                new Callback4.EmptyCallback<DialogInterface>() {
                                    @Override
                                    public void onYes(DialogInterface dialogInterface) {
                                        super.onYes(dialogInterface);
                                        PreferUser.get().logout();
                                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                        startActivity(intent);
                                    }
                                });
                        break;

                }
            }
        });
    }

    private void upload(String file, ImageView view) {
        uploadAvatarSubscription = MRetrifit.get()
                .uploadAvatar(new File(file), new Callback.EmptyCallback<AccessToken<HeadPicture>>() {
                    @Override
                    public void onPreExecute() {
                        UIUtils.showDialog(mProgressDialog);
                    }

                    @Override
                    public void onPostExecute() {
                        UIUtils.dismissDialog(mProgressDialog);
                    }

                    @Override
                    public void onSuccess(AccessToken<HeadPicture> headPictureAccessToken) {
                        super.onSuccess(headPictureAccessToken);
                        String headpictureurl = headPictureAccessToken.getLisTt().get(0).getHeadpictureurl();
                        PreferUser.get().setHeadPicture(headpictureurl);
                        PreferUser.get().saveUserInfo();

                        Glide.with(getContext())
                                .load(headpictureurl)
                                .bitmapTransform(new CropCircleTransformation(getContext()))
                                .into(view);
                    }

                    @Override
                    public void onError(Exception e) {
                        e.printStackTrace();
                    }
                });
    }

    //获取网络数据
    private List<UserFragmentEntity> getData() {

        List<UserFragmentEntity> list = new ArrayList<>();
        UserShow userShow = new UserShow("请登陆");
        if (PreferUser.get().isLogin()) {
            PreferUser.get().readLoginInfo();
            userShow.setName(PreferUser.get().getNickName() == "" ? PreferUser.get().getUserId()
                    : PreferUser.get().getNickName()).setIntro("").setImageurl(PreferUser.get().getHeadPicture());
        }
        UserFragmentEntity<UserShow> userShowUserFragmentEntity = new UserFragmentEntity<>(CLICK_ITEM_CHILD_VIEW);
        userShowUserFragmentEntity.setT(userShow);
        list.add(userShowUserFragmentEntity);
        list.add(new UserFragmentEntity(NEST_CLICK_ITEM_CHILD_VIEW));
        list.add(new UserFragmentEntity(CLICK_ITEM_VIEW));
        return list;
    }

    //fragment的显示监听
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            Log.i("hepan", "显示封面4");
        }
    }
}
